package com.falcon.service.impl;

import com.falcon.config.GeneratorConfig;
import com.falcon.domain.po.ApiPO;
import com.falcon.scanner.IControllerScanner;
import com.falcon.service.IGenApiService;
import com.falcon.domain.vo.ApiMethodMeta;
import com.falcon.domain.vo.ControllerMeta;
import com.falcon.mapper.IApiMapper;
import com.swan.core.utils.NameUtil;
import com.swan.mybatis.condition.Condition;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zongf
 * @date 2024-03-14
 **/
@Slf4j
@Service
public class GenApiService implements IGenApiService {

    @Autowired
    private IApiMapper apiMapper;

    @Autowired
    private IControllerScanner apiScanner;

    @Autowired
    protected GeneratorConfig generatorConfig;

    @Override
    public void sync() {

        // 清空表数据
        this.apiMapper.deleteList(Condition.newInstance());

        // 扫描项目中所有组件
        List<ControllerMeta> scanComponents = apiScanner.doScan(true, false, false);

        scanComponents.forEach(controllerMeta -> {

            // 保存 Controller
            ApiPO controllerApiPO = new ApiPO();
            controllerApiPO.setModuleName(controllerMeta.getModuleName());
            controllerApiPO.setName(controllerMeta.getSimpleName());
            controllerApiPO.setDescription(controllerMeta.getDescription());
            controllerApiPO.setRequestUri(controllerMeta.getRequestUri());
            controllerApiPO.setStatus(1);
            this.apiMapper.insertNotNull(controllerApiPO);

            // 保存方法
            for (ApiMethodMeta apiMethodMeta : controllerMeta.getApiMethodMetas()) {
                ApiPO methodApiPO = new ApiPO();
                methodApiPO.setParentId(controllerApiPO.getId());
                methodApiPO.setName(apiMethodMeta.getName());
                methodApiPO.setHttpMethod(apiMethodMeta.getHttpMethod());
                methodApiPO.setRequestUri(apiMethodMeta.getRequestUri());
                methodApiPO.setDescription(apiMethodMeta.getDescription());
                methodApiPO.setPerms(getPerms(controllerApiPO.getModuleName(), controllerApiPO.getName(), methodApiPO.getName()));
                methodApiPO.setStatus(1);
                this.apiMapper.insertNotNull(methodApiPO);
            }
        });
    }

    private String getPerms(String moduleName, String className, String methodName){
        // 权限标识符: module:controller:method
        String first = NameUtil.firstLowercase(moduleName);
        String second = NameUtil.firstLowercase(StringUtils.substringBefore(className, "Controller"));
        String last = NameUtil.firstLowercase(methodName);
        return String.format("%s:%s:%s", first, second, last);
    }
}
